/**
 * 保存管理器 - 处理文件保存功能
 */
class SaveManager {
    constructor() {
        this.currentFile = null;
        this.currentPath = null;
        this.isLoggedIn = false;
        this.init();
    }

    init() {
        this.bindEvents();
        this.updateSaveOptions();
        
        // 监听登录状态变化
        document.addEventListener('authStateChanged', (e) => {
            this.isLoggedIn = e.detail.isLoggedIn;
            this.updateSaveOptions();
        });
    }

    bindEvents() {
        // 主保存按钮
        document.getElementById('save-file').addEventListener('click', () => {
            this.handleMainSave();
        });

        // 下拉菜单切换
        document.getElementById('save-dropdown-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleDropdown();
        });

        // 保存选项
        document.getElementById('save-local').addEventListener('click', () => {
            this.saveToLocal();
            this.hideDropdown();
        });

        document.getElementById('save-account').addEventListener('click', () => {
            this.saveToAccount();
            this.hideDropdown();
        });

        document.getElementById('save-as').addEventListener('click', () => {
            this.saveAs();
            this.hideDropdown();
        });

        // 点击外部关闭下拉菜单
        document.addEventListener('click', () => {
            this.hideDropdown();
        });

        // 阻止下拉菜单内部点击事件冒泡
        document.getElementById('save-dropdown-menu').addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }

    updateSaveOptions() {
        const saveAccountBtn = document.getElementById('save-account');
        if (saveAccountBtn) {
            saveAccountBtn.disabled = !this.isLoggedIn;
            if (!this.isLoggedIn) {
                saveAccountBtn.title = '请先登录';
            } else {
                saveAccountBtn.title = '';
            }
        }
    }

    toggleDropdown() {
        const menu = document.getElementById('save-dropdown-menu');
        menu.classList.toggle('show');
    }

    hideDropdown() {
        const menu = document.getElementById('save-dropdown-menu');
        menu.classList.remove('show');
    }

    handleMainSave() {
        // 根据当前状态决定默认保存行为
        if (this.currentFile && this.currentPath) {
            // 如果有当前文件，直接保存
            if (this.currentPath.startsWith('account://')) {
                this.saveToAccount();
            } else {
                this.saveToLocal();
            }
        } else {
            // 新文件，显示另存为对话框
            this.saveAs();
        }
    }

    saveToLocal() {
        const content = window.editor ? window.editor.getValue() : '';
        const filename = this.currentFile || 'untitled.md';
        
        this.downloadFile(content, filename);
        this.showToast('文件已下载到本地', 'success');
    }

    async saveToAccount() {
        if (!this.isLoggedIn) {
            this.showToast('请先登录', 'error');
            return;
        }

        const content = window.editor ? window.editor.getValue() : '';
        const filename = this.currentFile || 'untitled.md';

        try {
            // 显示保存对话框
            const result = await this.showSaveDialog(filename);
            if (!result) return;

            // 模拟API调用
            const response = await this.mockSaveToAccount(result.path, content);
            
            if (response.success) {
                this.currentFile = result.filename;
                this.currentPath = `account://${result.path}`;
                this.showToast('文件已保存到我的文件', 'success');
                
                // 触发文件列表更新
                document.dispatchEvent(new CustomEvent('fileListUpdate'));
            } else {
                throw new Error(response.message || '保存失败');
            }
        } catch (error) {
            console.error('保存到账户失败:', error);
            this.showToast('保存失败: ' + error.message, 'error');
        }
    }

    async saveAs() {
        const content = window.editor ? window.editor.getValue() : '';
        
        try {
            const result = await this.showSaveAsDialog();
            if (!result) return;

            if (result.location === 'local') {
                this.downloadFile(content, result.filename);
                this.showToast('文件已下载到本地', 'success');
            } else if (result.location === 'account') {
                if (!this.isLoggedIn) {
                    this.showToast('请先登录', 'error');
                    return;
                }
                
                const response = await this.mockSaveToAccount(result.path, content);
                if (response.success) {
                    this.currentFile = result.filename;
                    this.currentPath = `account://${result.path}`;
                    this.showToast('文件已保存到我的文件', 'success');
                    
                    // 触发文件列表更新
                    document.dispatchEvent(new CustomEvent('fileListUpdate'));
                } else {
                    throw new Error(response.message || '保存失败');
                }
            }
        } catch (error) {
            console.error('另存为失败:', error);
            this.showToast('保存失败: ' + error.message, 'error');
        }
    }

    downloadFile(content, filename) {
        const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    async showSaveDialog(defaultFilename) {
        return new Promise((resolve) => {
            const modal = this.createSaveModal(defaultFilename, false);
            document.body.appendChild(modal);
            
            const filenameInput = modal.querySelector('#save-filename');
            const pathSelect = modal.querySelector('#save-path');
            const confirmBtn = modal.querySelector('#save-confirm');
            const cancelBtn = modal.querySelector('#save-cancel');
            
            filenameInput.focus();
            filenameInput.select();
            
            confirmBtn.addEventListener('click', () => {
                const filename = filenameInput.value.trim();
                const path = pathSelect.value;
                
                if (!filename) {
                    this.showToast('请输入文件名', 'error');
                    return;
                }
                
                document.body.removeChild(modal);
                resolve({
                    filename: filename,
                    path: path + '/' + filename
                });
            });
            
            cancelBtn.addEventListener('click', () => {
                document.body.removeChild(modal);
                resolve(null);
            });
            
            // ESC键取消
            const handleKeydown = (e) => {
                if (e.key === 'Escape') {
                    document.body.removeChild(modal);
                    document.removeEventListener('keydown', handleKeydown);
                    resolve(null);
                }
            };
            document.addEventListener('keydown', handleKeydown);
        });
    }

    async showSaveAsDialog() {
        return new Promise((resolve) => {
            const modal = this.createSaveModal('untitled.md', true);
            document.body.appendChild(modal);
            
            const filenameInput = modal.querySelector('#save-filename');
            const pathSelect = modal.querySelector('#save-path');
            const locationSelect = modal.querySelector('#save-location');
            const confirmBtn = modal.querySelector('#save-confirm');
            const cancelBtn = modal.querySelector('#save-cancel');
            
            filenameInput.focus();
            filenameInput.select();
            
            // 位置变化时更新路径选项
            locationSelect.addEventListener('change', () => {
                pathSelect.style.display = locationSelect.value === 'account' ? 'block' : 'none';
            });
            
            confirmBtn.addEventListener('click', () => {
                const filename = filenameInput.value.trim();
                const location = locationSelect.value;
                const path = pathSelect.value;
                
                if (!filename) {
                    this.showToast('请输入文件名', 'error');
                    return;
                }
                
                document.body.removeChild(modal);
                resolve({
                    filename: filename,
                    location: location,
                    path: location === 'account' ? path + '/' + filename : filename
                });
            });
            
            cancelBtn.addEventListener('click', () => {
                document.body.removeChild(modal);
                resolve(null);
            });
        });
    }

    createSaveModal(defaultFilename, showLocation = false) {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>${showLocation ? '另存为' : '保存文件'}</h3>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="save-filename">文件名:</label>
                        <input type="text" id="save-filename" value="${defaultFilename}" class="form-input">
                    </div>
                    ${showLocation ? `
                    <div class="form-group">
                        <label for="save-location">保存位置:</label>
                        <select id="save-location" class="form-select">
                            <option value="local">本地下载</option>
                            <option value="account" ${this.isLoggedIn ? '' : 'disabled'}>我的文件</option>
                        </select>
                    </div>
                    ` : ''}
                    <div class="form-group" ${showLocation ? 'style="display: none;"' : ''}>
                        <label for="save-path">保存路径:</label>
                        <select id="save-path" class="form-select">
                            <option value="/documents">文档</option>
                            <option value="/projects">项目</option>
                            <option value="/notes">笔记</option>
                            <option value="/drafts">草稿</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="save-cancel" class="btn btn-secondary">取消</button>
                    <button id="save-confirm" class="btn btn-primary">保存</button>
                </div>
            </div>
        `;
        return modal;
    }

    async mockSaveToAccount(path, content) {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 模拟保存成功
        return {
            success: true,
            path: path,
            size: content.length,
            lastModified: new Date().toISOString()
        };
    }

    showToast(message, type = 'info') {
        // 使用现有的toast系统
        if (window.showToast) {
            window.showToast(message, type);
        } else {
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
    }

    // 设置当前文件信息
    setCurrentFile(filename, path) {
        this.currentFile = filename;
        this.currentPath = path;
    }

    // 获取当前文件信息
    getCurrentFile() {
        return {
            filename: this.currentFile,
            path: this.currentPath
        };
    }
}

// 初始化保存管理器
window.saveManager = new SaveManager();